#include "gsm_tools.h"
#include "gsm_usart.h"
#include "gsm_zip.h"


/*! \brief Used to get index of newly received message
 *
 *  Will search through the receive buffer found in AVRSMS_com.c, until a \n
 *  ',' is found. If this charcter is found in the buffer, the next parameter will \n
 *  be the new message index.
 *
 *  \param    void
 *
 *  \retval   i index of new message
 *  \retval   0 Error with echo off
 */
int TOOLS_DecodeCMTI(void)
{
  unsigned char *temp;
  unsigned int length, i;

  length = 0;

  length = USART_Trim();                                     //Trim off trailing OK\r\n
  temp = USART_GetS();                                     //Get rx_buff

  for(i = 0; (i < length) && (*temp++ != ','); i++)    //Loop until we get a ','
  {
    ;
  }

  //Error
  if(i >= length)
  {
    return 0;
  }
  else
  {
    return ZIP_AtoI(temp);                             //Convert ascii int to integer
  }
}


/*! \brief Get start of compressed string
 *
 *  When a new message has been read from a given index, this function\n
 *  will run through it, and find start of the encoded user text.
 *
 *  \param    void
 *
 *  \retval   in_handle if error in_handle points to '\0', else it will point to the string ready for decompression
 *
 */
unsigned char* TOOLS_DecodeCMGR(int index)
{
  unsigned char *in_handle;
  int i, len, field_length;

  len = USART_Trim();                                   //Trim off OK\r\n
  in_handle = USART_GetS();                                  //Get rx_buff

  in_handle += 2;                                             //Skip first \r\n

  for(i = 0; (i < len) && (*in_handle++ != '\n'); i++)   //Loop until we get '\n'
  {
    ;
  }

  if(i >= len)
  {
    in_handle = '\0';
    return in_handle;
  }
  else
  {
    field_length = 16 * ZIP_HtoI(*in_handle++);
    field_length = ZIP_HtoI(*in_handle++);

    in_handle += 2 * field_length + 2;                        //Skip Service center nmbr

    //Find length of sender address
    field_length = 16 * ZIP_HtoI(*in_handle++);
    field_length = ZIP_HtoI(*in_handle++);

    if(field_length % 2)
    {
      field_length++;                                     //Check for trailing F
    }

    in_handle += 2 + field_length;                          //Skip fields in header

    in_handle += 14 + 4;                                    //Skip more fields...TP-PID, TP-DCS and TP-SCTS

    return (in_handle + 2);                               //Return correct pointer
  }
}